package top.lyc829.zzl_android.ui.team.my_team.people;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.google.android.material.tabs.TabLayout;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.imageview.RadiusImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kotlin.Lazy;
import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.PeopleFragmentBinding;
import top.lyc829.zzl_android.logic.bean.ActivityBean;
import top.lyc829.zzl_android.logic.bean.NoticeCommentBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.UserInfoBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.main.LazyFragment;
import top.lyc829.zzl_android.ui.message.replay.ReplayAdapter;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.team.my_team.MyTeamViewModel;

public class PeopleFragment extends LazyFragment {

    private MyTeamViewModel mViewModel;
    private PeopleFragmentBinding binding;
    private boolean canQuit = false;
    PeopleAdapter adapter;



    public static PeopleFragment newInstance() {
        return new PeopleFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = PeopleFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(requireActivity()).get(MyTeamViewModel.class);

    }

    @Override
    public void lazyInit() {
        initRecycler();
        initData();

        initTab();

        observer();
        clickListener();



    }

    private void initTab() {

        binding.activityTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (mViewModel.getTeamId().getValue() != null && mViewModel.getActivitiesLivaData().getValue() != null) {
                    int activityId = mViewModel.getActivitiesLivaData().getValue().get(tab.getPosition()).getId();
                    mViewModel.getPeopleInActivity(mViewModel.getTeamId().getValue(), activityId);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void initRecycler() {
        adapter = new PeopleAdapter();
        binding.teamPeopleRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.teamPeopleRecycler.setAdapter(adapter);
        adapter.setAnimationEnable(true);   // recyclerview加载动画
    }

    private void clickListener() {
        binding.btnExitTeam.setOnClickListener(v -> {
            new MaterialDialog.Builder(getContext())
                    .title("确定退出该团队?")
                    .content("队长退出团队后团队、活动、游记将都被删除！")
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive((dialog, which) -> {
                        quitTeam();
                    })
                    .show();
        });

        adapter.setOnItemClickListener((adapter1, view, position) -> {
            UserInfoBean userInfo = adapter.getItem(position);
            Intent intent = new Intent(getActivity(), OtherUserDetailActivity.class);
            intent.putExtra("id", userInfo.getId());
            startActivity(intent);
        });

    }

    private void quitTeam() {
        if (!canQuit) {
            Utils.Sout("lost teamId");
            Utils.showToast("退出失败");
            return;
        }
        Network.quitTeam(mViewModel.getTeamId().getValue(), Utils.getUserId(), new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                ResultBean<Void> resultBean = JsonUtilNew
                        .fromJsonObject(res.body().string(), Void.class);

                if (resultBean.getCode().equals(200)) {
                    getActivity().runOnUiThread(() -> {
                        Utils.showToast("退出成功");
                        LiveEventBus
                                .get("team_change")
                                .post(1);
                        getActivity().finish();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }


    private void observer() {

        mViewModel.getActivitiesLivaData().observe(getViewLifecycleOwner(), activityBeans -> {
            mViewModel.getPeopleInActivity(mViewModel.getTeamId().getValue(), activityBeans.get(0).getId());
            binding.activityTab.removeAllTabs();
            for (int i = 1; i <= activityBeans.size(); i++) {
                binding.activityTab.addTab(binding.activityTab.newTab().setText("活动" + i));
            }
        });

        mViewModel.getTeamId().observe(getViewLifecycleOwner(), integer -> {
            canQuit = true;
            // mViewModel.getPeopleFromServer(integer);

        });


        mViewModel.getPeopleLiveData().observe(getViewLifecycleOwner(), userInfoBeans -> {
            if (userInfoBeans == null || userInfoBeans.size() == 0) {
                binding.tvPeopleNumber.setText("共0人 >");
            } else {
                binding.tvPeopleNumber.setText("共" + userInfoBeans.size() + "人 >");
            }
            adapter.setList(userInfoBeans);
        });
    }

    private void initData() {


    }


}